#!/bin/bash

CONTENTS_DIR="$(cd "$(dirname "$0")/.." && pwd)"
RESOURCE_DIR="$CONTENTS_DIR/Resources"
APP_DIR="$(cd "$CONTENTS_DIR/.." && pwd)"
PRINT_HELPER_DIR="$(cd "$APP_DIR/.." && pwd)"
SUPPORT_DIR="$HOME/Library/Application Support/WhatnotPrintHelper"
PLIST_NAME="com.whatnot.capture.printhelper.plist"
PLIST_PATH="$HOME/Library/LaunchAgents/$PLIST_NAME"
LOG_PATH="$HOME/Library/Logs/whatnot-print-helper.log"
PYTHON="$(command -v python3)"
INSTALL_WAIT_PID=""

fail() {
  install_wait_end
  osascript -e "display alert \"Whatnot Printing\" message \"$1\" as critical"
  exit 1
}

escape_applescript() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

notify() {
  local msg
  msg="$(escape_applescript "$1")"
  osascript -e "display notification \"${msg}\" with title \"Whatnot Printing\"" 2>/dev/null || true
}

install_wait_start() {
  osascript <<'APPLESCRIPT' &
display dialog "Installing Whatnot Printing…" & return & return & "In progress — please wait a few seconds." with title "Whatnot Printing" with icon note giving up after 600
APPLESCRIPT
  INSTALL_WAIT_PID=$!
}

install_wait_end() {
  if [ -n "$INSTALL_WAIT_PID" ]; then
    kill "$INSTALL_WAIT_PID" 2>/dev/null || true
    wait "$INSTALL_WAIT_PID" 2>/dev/null || true
    INSTALL_WAIT_PID=""
  fi
}

trap install_wait_end EXIT

clear_download_quarantine() {
  xattr -cr "$PRINT_HELPER_DIR" 2>/dev/null || true
  xattr -cr "$APP_DIR" 2>/dev/null || true
}

block_if_incomplete_folder() {
  if [ -f "$PRINT_HELPER_DIR/print_server.py" ] || [ -f "$PRINT_HELPER_DIR/Install Print Helper.command" ]; then
    return 0
  fi

  osascript <<'APPLESCRIPT'
display alert "Unzip the full folder first" message "macOS opened a temporary copy of the installer.

1. Close this window
2. In Downloads, unzip print-helper-mac.zip fully
3. Double-click Install Print Helper.command" buttons {"OK"} default button "OK" with title "Whatnot Printing"
APPLESCRIPT
  exit 1
}

show_complete() {
  osascript - "$1" "$2" <<'APPLESCRIPT'
on run argv
  display alert (item 1 of argv) message (item 2 of argv) buttons {"OK"} default button "OK" with title "Whatnot Printing"
end run
APPLESCRIPT
}

list_mac_printers() {
  lpstat -p 2>/dev/null | awk '/^printer / {print $2}'
}

pick_best_printer() {
  local best=""
  local p
  while read -r p; do
    [ -z "$p" ] && continue
    if echo "$p" | grep -qiE 'thermal|rollo|label'; then
      best="$p"
      break
    fi
  done < <(list_mac_printers)
  echo "$best"
}

applescript_printer_list() {
  local items=()
  local p
  while read -r p; do
    [ -n "$p" ] && items+=("$p")
  done < <(list_mac_printers)
  if [ ${#items[@]} -eq 0 ]; then
    echo ""
    return
  fi
  local apple=""
  local item
  for item in "${items[@]}"; do
    local escaped="${item//\\/\\\\}"
    escaped="${escaped//\"/\\\"}"
    apple+="\"$escaped\", "
  done
  apple="${apple%, }"
  osascript <<EOF
set printerList to {$apple}
set picked to choose from list printerList with prompt "Which printer should labels use?" with title "Whatnot Printing"
if picked is false then
  return "CANCEL"
end if
return item 1 of picked
EOF
}

choose_printer() {
  local count
  count="$(list_mac_printers | grep -c . || true)"

  if [ "$count" -eq 0 ]; then
    osascript <<'APPLESCRIPT'
display alert "No printer found" message "Add your Rollo in System Settings → Printers & Scanners, then run this installer again." buttons {"Open Printers", "OK"} default button "Open Printers"
if button returned of result is "Open Printers" then
  do shell script "open 'x-apple.systempreferences:com.apple.preference.printfax'"
end if
APPLESCRIPT
    exit 1
  fi

  if [ "$count" -eq 1 ]; then
    list_mac_printers | head -n 1
    return
  fi

  local best
  best="$(pick_best_printer)"
  if [ -n "$best" ]; then
    local choice
    choice="$(osascript <<EOF
set dlg to display dialog "Found your label printer:

$best

Use this one?" buttons {"Pick Another…", "Use This Printer"} default button "Use This Printer" with title "Whatnot Printing"
return button returned of dlg
EOF
)"
    if [ "$choice" = "Use This Printer" ]; then
      echo "$best"
      return
    fi
  fi

  applescript_printer_list
}

# --- Step 1: Welcome ---
clear_download_quarantine
block_if_incomplete_folder

WELCOME="$(osascript <<'APPLESCRIPT'
set dlg to display dialog "Set up background printing for the Whatnot Sold Items extension.

Make sure your Rollo printer is already installed!" buttons {"Cancel", "Continue"} default button "Continue" with title "Whatnot Printing"
if button returned of dlg is "Cancel" then
  return "CANCEL"
end if
return "OK"
APPLESCRIPT
)"

if [ "$WELCOME" = "CANCEL" ]; then
  exit 0
fi

# --- Step 2: Prerequisites ---
if [ -z "$PYTHON" ]; then
  fail "Python 3 is required. Install Xcode Command Line Tools (xcode-select --install), then run this installer again."
fi

if [ ! -x /usr/bin/lp ] && ! command -v lp >/dev/null 2>&1; then
  fail "macOS printing was not found. Add your Rollo in System Settings → Printers & Scanners first."
fi

# --- Step 3: Printer ---
PRINTER="$(choose_printer)"
if [ "$PRINTER" = "CANCEL" ] || [ -z "$PRINTER" ]; then
  exit 0
fi

# --- Step 4: Install (one “in progress” dialog, then Complete) ---
notify "Installing… please wait."
install_wait_start

mkdir -p "$SUPPORT_DIR"
cp "$RESOURCE_DIR/print_server.py" "$SUPPORT_DIR/print_server.py"
chmod 644 "$SUPPORT_DIR/print_server.py"
mkdir -p "$HOME/Library/LaunchAgents"

cat > "$PLIST_PATH" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.whatnot.capture.printhelper</string>
  <key>ProgramArguments</key>
  <array>
    <string>$PYTHON</string>
    <string>$SUPPORT_DIR/print_server.py</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>/usr/bin:/bin:/usr/sbin:/sbin</string>
    <key>ROLLO_PRINTER</key>
    <string>$PRINTER</string>
    <key>PRINT_MODE</key>
    <string>pdf</string>
    <key>LABEL_PAGE_SIZE</key>
    <string>2x1</string>
    <key>PRINT_DPI</key>
    <string>203dpi</string>
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>$LOG_PATH</string>
  <key>StandardErrorPath</key>
  <string>$LOG_PATH</string>
</dict>
</plist>
EOF

launchctl bootout "gui/$(id -u)" "$PLIST_PATH" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST_PATH" || fail "Could not start the print helper. Try running the installer again."
launchctl enable "gui/$(id -u)/com.whatnot.capture.printhelper" 2>/dev/null || true
launchctl kickstart -k "gui/$(id -u)/com.whatnot.capture.printhelper" 2>/dev/null || true

QUEUE="$PRINTER"
if ! lpstat -p "$QUEUE" >/dev/null 2>&1; then
  QUEUE="$(lpstat -p 2>/dev/null | awk '/^printer / {print $2}' | while read -r q; do
    n=$(echo "$q" | tr '_' ' ')
    if [ "$q" = "$PRINTER" ] || [ "$n" = "$PRINTER" ]; then echo "$q"; break; fi
  done)"
fi

LPOPTS_PID=""
if [ -n "$QUEUE" ]; then
  lpoptions -p "$QUEUE" -o PageSize=2x1 -o Resolution=203dpi -o roMediaTracking=Gap 2>/dev/null || true &
  LPOPTS_PID=$!
fi

READY=0
TRIES=0
while [ "$TRIES" -lt 40 ]; do
  if curl -sf --max-time 1 "http://127.0.0.1:3737/health" >/dev/null; then
    READY=1
    break
  fi
  TRIES=$((TRIES + 1))
  sleep 0.1
done

if [ -n "$LPOPTS_PID" ]; then
  wait "$LPOPTS_PID" 2>/dev/null || true
fi

if [ "$READY" -eq 1 ]; then
  curl -sf --max-time 5 -X POST "http://127.0.0.1:3737/configure" \
    -H "Content-Type: application/json" \
    -d "{\"printerName\":\"$PRINTER\"}" >/dev/null || true
fi

install_wait_end
trap - EXIT

if [ "$READY" -eq 1 ]; then
  notify "Complete!"
  show_complete "Complete!" "Printer: $PRINTER

1. Reload the Chrome extension
2. Turn on Auto-print labels
3. Click Test print"
else
  notify "Installed — try Test print in a few seconds"
  show_complete "Installed" "Print helper is still starting.

Reload the extension in a few seconds and try Test print."
fi
